import React from "react";
import logo from "@/assets/images/logo#000.png";
import wxGong from "@/assets/images/wxGong.png";
import NewLogo from "@/assets/images/NewLogo.jpg";

import printJs from "print-js";
import JsBarcode from "jsbarcode";
import { makeCode } from "@/utils/makeCode";
import printStyle from './printStyle'
import { unitConversion } from './unitConversion'
import $ from 'jquery'
function createTable(ths, trs) {
    // 创建数据表格
    const table = $("<table border='0' cellPadding='0' cellSpacing='0' style='page-break-after:always;'></table>")
    const thead = $('<thead></thead>')
    const tbody = $('<tbody></tbody>')
    //订单描述区域注入内容
    thead.html(ths)
    tbody.html(trs)
    table.append(thead)
    table.append(tbody)
    return table
}

/**
 * 打印
 * Item {
 *  th:Array[{label:String,value:String,width:String}],订单表头列
 *  data:Object[],数据源
 *  title:String,标题
 *  infos:Array[{label:String,value:String}]详情描述
 * }
 * @param {Item[]} dataSource
 */
export function toPrintTool(dataSource = []) {
    const px2mm = parseFloat((new unitConversion().pxConversionMm(1)).toFixed(2))
    const maxCount = 4
    //打印内容区域
    let printContent = $(`<div></div>`);
    console.log(dataSource, 'dataSource');
    dataSource.forEach(row => {
        const { th, data, infos, title, tfoot, remark } = row
        // 标题
        let ths = "<tr><th colspan='" + th.length + "'>" + title + "</th></tr>"
        //订单描述内容
        infos.forEach((item, index) => {
            console.log(index % 3);
            if (index % 3 === 0) {
                ths += '<tr> <th class="info_col"  colspan="' + th.length + '">'
            }
            ths += `<span>${item.label || ''}：${item.value || ''}</span>`
            if (index % 3 === 2 || index === infos.length - 1) {
                ths += '</th></tr>'
            }
        })
        ths += "<tr><th colspan='" + th.length + "' class='info_col remark'><div>备注：" + remark + "</div></th></tr>"
        // 组装数据
        let thObj = {}
        th.forEach((td, index) => {
            thObj[td.value] = td.label
        })
        data.unshift(thObj)
        data.push({ ...tfoot })
        const resultData = data.reduce((prev, cur, index, arr) => {
            if (index === arr.length - 1) {
                let tableFoot = "<tr><td colspan='" + th.length + "' class='border0'><div class='tableFoot'>"
                Object.keys(tfoot).forEach(key => {
                    tableFoot += `<span>${key}:</span>`
                })
                tableFoot += "<div></td></tr>"
                prev += tableFoot + '%breakPage%'  // 添加表尾
                return prev
            }
            let str = '<tr>'
            th.forEach(td => {
                if (td.align && index > 0) {
                    str += '<td width="' + td.width + '"><div class="text" data-pageNo="" style="">' + (cur[td.value] || '') + '</div></td>'
                } else {
                    str += '<td width="' + td.width + '"><div class="text" data-pageNo="" style="align-items:center;">' + (cur[td.value] || '') + '</div></td>'
                }
            })
            str += '</tr>'
            prev += (index % maxCount === 0 && index > 0 ? '%breakPage%' + str : str)

            return prev
        }, '')
        resultData.split('%breakPage%').forEach(item => {

            item && printContent.append(createTable(ths, item))
        })
    })
    // 注入页码
    const tables = printContent.find('table')
    const pageTotal = tables.length
    for (let index = 0; index < tables.length; index++) {
        $(tables[index]).attr('data-pageNo', `第${index + 1}/${pageTotal}页`)
    }
    //注入打印内容
    const dom = document.createElement('div')
    dom.setAttribute('id', 'printDom')
    dom.setAttribute('class', 'printDom')
    $(dom).html(printContent.html())
    document.body.appendChild(dom);
    printJs({
        printable: "printDom",
        type: "html",
        style: printStyle(px2mm), // 亦可使用引入的外部css;
        scanStyles: false,

    });
    document.body.removeChild(document.querySelector("#printDom"));
}

export function printOutLibraryOrder(dataSource) {
    let table = ''
    let dom = ''
    console.log(dataSource)
    const info = `
  <div class='title'>${dataSource.libraryName}出库单</div>
  <div class="info">
      <div class="row">
          <div class="col">
              <span class="label">仓库名称:</span>
              <span class="val">${dataSource.libraryName ? dataSource.libraryName : ''}</span>
          </div>
          <div class="col">
              <span class="label">出库时间:</span>
              <span class="val">${dataSource.outLibraryTime ? dataSource.outLibraryTime : ''}</span>
          </div>
          <div class="col">
              <span class="label">出库单号:</span>
              <span class="val">${dataSource.code ? dataSource.code : ''}</span>
          </div>
      </div>
      <div class="row">
          <div class="col">
              <span class="label">对应单号:</span>
              <span class="val">${dataSource.dataCode ? dataSource.dataCode : ''}</span>
          </div>
          <div class="col">
              <span class="label">备注:</span>
              <span class="val">${dataSource.remark ? dataSource.remark : ''}</span>      
          </div>
          <div class="col">
              <span class="label">快递公司:</span>
              <span class="val"></span>      
          </div>
      </div>
      <div class="row">
          <div class="col">
              <span class="label">快递单号:</span>
              <span class="val">${dataSource.courierNo ? dataSource.courierNo : ''}</span>      
          </div>
      </div>
  </div>`

    let head = `
          <tr>
          <td width="100px">序号</td>
          <td width="100px">物料编码</td>
          <td width="180px">物料名称</td>
          <td width="130px">规格型号</td>
          <td width="30px">数量</td>
          <td width="50px">单价</td>
          <td width="50px">金额</td>
          <td width="100px">仓库</td>
          <td width="110px">备注</td>
      </tr>`
    let resultDom = ''
    let countTotalResult = 0
    let priceTotalResult = 0
    // 混入合计，签字
    dataSource.stockOutLibraryInfoPrintVoList.push({
        countTotalResult,
        priceTotalResult
    })
    dataSource.stockOutLibraryInfoPrintVoList.push({
        zdrName: '',
        fahuoName: '',
        fuheName: '',
        shName: '',
    })
    const pageTotal = Math.ceil(dataSource.stockOutLibraryInfoPrintVoList.length / 6)


    dataSource.stockOutLibraryInfoPrintVoList.forEach((item, index) => {
        if (index % 6 === 0) {
            dom = `${info} `
            table = ''
            if (index === 0) {
                table = head
            }

        }

        if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
            table += `<tr>
              <td width="100px">合计：</td>
              <td width="180px"></td>
              <td width="130px"></td>
              <td width="30px">${countTotalResult}</td>
              <td width="50px"></td>
              <td width="50px">${priceTotalResult}</td>
              <td width="100px"></td>
              <td width="110px"></td>
          </tr>`
        } else if (index < dataSource.stockOutLibraryInfoPrintVoList.length - 2) {
            countTotalResult += item.count ? item.count : 0
            priceTotalResult += parseFloat(item.totalPrice >= 0 ? ((item.totalPrice) / 100).toFixed(2) : 0)
            table += `<tr>
          <td width="10px"><div>${index + 1}</div></td>
          <td width="100px"><div>${item.materialId ? item.materialId : ''}</div></td>
          <td width="180px"><div>${item.materialName ? item.materialName : ''}</div></td>
          <td width="130px"><div>${item.skuStr ? item.skuStr : ''}</div></div></td>
          <td width="30px"><div>${item.count ? item.count : 0}</div></td>
          <td width="50px"><div>${item.unitPrice ? ((item.unitPrice) / 100).toFixed(2) : 0}</div></td>
          <td width="50px"><div>${item.totalPrice ? ((item.totalPrice) / 100).toFixed(2) : 0}</div></td>
          <td width="100px"><div>${item.libraryName ? item.libraryName : ''}</div></td>
          <td width="110px"><div>${item.remark ? item.remark : ''}</div></td>
      </tr>`
        }

        if (index % 6 === 5 || index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
            dom += `  
          <div class="goodsInfo">
             <table border='1' cellPadding='0' cellSpacing='0' align="center">
                 <tbody>
                    ${table}
                 </tbody>
             </table>
          </div>
          <div class="pageNo">第${Math.ceil(index / 6)}/${pageTotal}页</div>
          `
            if (index === dataSource.stockOutLibraryInfoPrintVoList.length - 1) {
                dom += `<div class="signName">
              <span>配货时间：</span>
              <span>发货人：</span>
              <span>复核人：</span>
              <span>审核人：</span>
          </div>`
            }
            resultDom += dom
        }
    })
    let style = `@page { margin: 0; }
  @media print {
      body { padding: 20px 50px 20px 70px;}
              .printDom{
                  width:750px;
                  height:450px;
                  position:relative;
                  font-size:12px;
              }
              .title{
                  height:30px;
                  font-weight:600;
                  font-size:16px;
                  text-align:center;
                   padding-top:55px;
              }
              .title:first-child{
                  padding-top:0px;

              }
              .pageNo{
                  text-align:right;
                  margin-top:5px;


              }
              .signName{
                  height:40px;
                  display:flex;
                  align-items:center;
                  justify-content: space-between;
              }
              .signName span{
                  flex:1;
                 
              }
              .info{
                  height:60px;
              }
              .row{
                  display:flex;
                  align-items:center;
                  justify-content: space-between;
                  font-size:12px;
                  margin-bottom:5px;
              }
              .col{
                  flex:1;
              }
              .label{
                  width:100px;
                  text-align:right;
              }
              .val{
                  width:200px;
              }
            
              td{
                  height:50px;
                  font-size:12px;
                  text-align:center;
              }
              td div{
                  width:100%;
                  height:50px;
                  overflow:hidden;
                  display:flex;
                  align-items:center;
                  justify-content: center;
                  white-space:normal;
                  word-break:break-all;
              }
          }
          `
    let div = document.createElement('div')
    div.innerHTML = resultDom
    div.setAttribute('id', 'print_area')
    div.setAttribute('class', 'printDom')
    document.body.appendChild(div)
    printJs({
        printable: 'print_area',
        type: 'html',
        style: style,// 亦可使用引入的外部css;
        scanStyles: false
    })
    document.body.removeChild(document.querySelector('#print_area'))

}



/**
 *
 * @param {*} dataSource
 * @param {*} productData
 * @param {boolean} flag  是否限时优惠价信息
 */
export function toPrint(dataSource, productData, flag) {
    console.log(productData);
    let table = "";
    productData.forEach((item, index) => {
        table += `<tr>
            <td>${index + 1}</td>
            <td>${item.materialName ?? item.goodsName}${item.giftId !== "0" ? "（赠）" : ""
            }</td>
            <td>${item.sku} </td>
            <td>${item.orderProductCount}</td>
            <td>${(item.orderPrice / 100).toFixed(2)}</td>
            ${flag
                ? //  `<td>${(item.orderPriceTotal / 100).toFixed(2)}</td>`+
                //  `<td>${(item.detailDiscountsPrice / 100).toFixed(2)}</td>`+
                `<td>${(item.detailPayPrice / 100).toFixed(2)}</td>`
                : " "
            }
        </tr>`;
    });
    let dom = `

                <h2 class='title'>出货单</h2>
                <img src="${logo}" alt="" class="logo" />
                <div class="info">
                    <div class="orderCode orderInfo">
                        <span class="label">订单编号：</span>
                        <span class="val">${dataSource.orderCode}</span>
                    </div>
                    <div class="orderTime orderInfo">
                        <span class="label">订单时间：</span>
                        <span class="val">${dataSource.createTime}</span>
                    </div>
                    <div class="storeName orderInfo">
                        <span class="label">商户名：</span>
                        <span class="val">${dataSource.storeName ? dataSource.storeName : ""
        }</span>
                    </div>
                    <div class="userInfo orderInfo">
                        <span class="label">客户信息：</span>
                        <span class="val">${dataSource.memberName
            ? makeCode(
                dataSource.memberName,
                "mid",
                1,
                dataSource.memberName.length - 1
            )
            : ""
        }，${dataSource.memberPhone ? makeCode(dataSource.memberPhone, "mid", 3, 7) : ""
        }</span>
                    </div>
                    <div class="address orderInfo">
                        <span class="label">收货信息：</span>
                        <span class="val">${dataSource.memberAddress
            ? dataSource.memberAddress
            : ""
        }</span>
                    </div>
                    <div class="goodsInfo">
                        <table border='1' cellPadding='10' cellSpacing='0'>
                            <thead>
                                <tr>
                                    <td>序号</td>
                                    <td>物料名称(商品名)</td>
                                    <td>规格</td>
                                    <td>数量</td>
                                    <td>单价</td>
                                    ${flag
            ? //  '<td>原价</td>'+
            // '<td>优惠金额</td>'+
            "<td>实付价</td>"
            : " "
        }
                                </tr>
                            </thead>
                            <tbody>
                               ${table}
                                <tr>
                                    <td colSpan="1">合计</td>
                                    <td>￥${(
            dataSource.orderTotalPrice / 100
        ).toFixed(2)}</td>
                                    <td colSpan="${flag ? 3 : 2}">实付金额</td>
                                    <td>￥${(
            dataSource.orderPayPrice / 100
        ).toFixed(2)}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="footer">
                    <div class="thanks">感谢您选择哈奇马宠物！</div>
                    <div class="tips">
                        <div class="tipsTitle">温馨提示：</div>
                        <div class="tipsText">
                        遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！
                        </div>
                    </div>
                </div>
          `;
    let style = `@page { margin: 0; } body { padding: 0px;}
            .printDom {
                position: relative;
                padding: 20px 20px 10px;
                background-color: aqua;
            
            }
            
            .printDom .logo {
                width: 150px;
                background-color: #000;
                position: absolute;
                left: 50px;
                top: 20px;
                color:#00;
            }
            
            .printDom .title {
                font-weight: 600;
                font-size: 32px;
                text-align: center;
            }
            
            .printDom .orderInfo {
                display: flex;
                align-items: center;
                font-size: 14px;
                letter-spacing: 2px;
            
            }
            
            .printDom .orderInfo .label {
                display: flex;
                width: 80px;
            }
            
            .printDom table {
                width:90%;
                margin-top: 4px;
            
            }
            
            .printDom table td {
                padding: 5px 20px;
                font-size: 14px;
                text-align: center;
            }
            
            .footer {
                font-size: 16px;
                margin-top: 4px;
            
            }
            
            .printDom .footer .thanks {
                text-align: left;
            }
            
            .printDom .footer .tips {
                text-align: left;
            
            }
            
            .printDom .footer .tipsText {
                font-weight: 600;
            }`;
    let div = document.createElement("div");
    div.innerHTML = dom;
    div.setAttribute("id", "print_area");
    div.setAttribute("class", "printDom");
    document.body.appendChild(div);
    printJs({
        printable: "print_area",
        type: "html",
        style: style, // 亦可使用引入的外部css;
        scanStyles: false,
    });
    document.body.removeChild(document.querySelector("#print_area"));
}
//合并发货打印面单
export function mergePrints(dataSource, flag) {
    let div = document.createElement("div");
    let body = "";
    let resData = []
    let pageNum = 0
    dataSource.forEach((item, index) => {
        let total = 0
        let totalReal = 0
        pageNum += 1
        item.orderDetailList.forEach((item2, index2) => {
            item2.sort = index2 + 1
            let arr = JSON.parse(item2.goodsSkuJson)
            item2.sku = arr.skuAttribute.map((j) => {
                return j.value
            })
            if (index2 === 0) {
                resData.push({
                    memberAddress: item.memberAddress, orderCode: item.orderCode, createTime: item.createTime, memberName: item.memberName
                        ? makeCode(item.memberName, "mid", 1, item.memberName.length - 1) : "", storeName: item.storeName ? item.storeName : "", memberPhone: item.memberPhone ? makeCode(item.memberPhone, "mid", 3, 7) : "",
                    isHead: true, ind: '序号', td1: '物料名称', td2: '规格', td3: '数量', td4: '单价', td5: '实付价'
                })
            }
            item2 = {
                ...item2, memberAddress: item.memberAddress, orderCode: item.orderCode, createTime: item.createTime, memberName: item.memberName
                    ? makeCode(item.memberName, "mid", 1, item.memberName.length - 1) : "", storeName: item.storeName ? item.storeName : "", memberPhone: item.memberPhone ? makeCode(item.memberPhone, "mid", 3, 7) : "",
            }
            totalReal += item2.detailPayPrice
            total += item2.orderPriceTotal
            resData.push(item2)

            if (index2 === item.orderDetailList.length - 1) {
                resData.push({
                    memberAddress: item.memberAddress, orderCode: item.orderCode, createTime: item.createTime, memberName: item.memberName
                        ? makeCode(item.memberName, "mid", 1, item.memberName.length - 1) : "", storeName: item.storeName ? item.storeName : "", memberPhone: item.memberPhone ? makeCode(item.memberPhone, "mid", 3, 7) : "",
                    isFoot: true, td6: '合计：￥' + total / 100, td7: '实付金额：￥' + totalReal / 100
                })
            }
        })
    })
    let count = 16, pageNo = 0, pageSize = 16
    pageNum = Math.ceil((resData.length + pageNum * 2) / count)
    resData.forEach((item, index) => {
        if (count <= 0) {
            count = pageSize
        }
        if (index === 0) {
            body += `
            <div class='header'>
            <h2 class='title'>出货单</h2>
             <img src="${logo}" alt="" class="logo" />
          </div>`
            count = 17
        }
        if (count >= pageSize) {
            pageNo += 1
            if (index !== 0) {
                body += `<div style="page-break-after:always;"></div>`
                body += `<div style="height:50px;"></div>`

            }
            body += `<div class="content" >
            <div class="descItem">订单编号：${item.orderCode}</div>
            <div class="descItem">订单时间：${item.createTime}</div>
            <div class="descItem">商户名称：${item.storeName}</div>
            <div class="descItem">客户信息：${item.memberName},${item.memberPhone}</div>
            <div class="descItem">收货信息：${item.memberAddress}</div>
            </div>
            `
            count = count - 2
            body += `<table border='1' cellPadding='0' cellSpacing='0'>`
            if (item.isFoot) {
                body += `
                <tr>
                <td colSpan="3" width="450px" ><div class="txt">${item.td6}</div></td>
                <td colSpan="3" width="250px"><div class="txt">${item.td7}</div></td>
                </tr>`
                body += `</tbody></table>`

            } else {
                if (item.isHead) {
                    body += `  
                    <tbody>
                      <tr>
                          <td width="50px"><div class="txt">${item.ind}</div></td>
                          <td width="200px"><div class="txt">${item.td1}</div></td>
                          <td width="200px"><div class="txt">${item.td2}</div></td>
                          <td width="50px"><div class="txt">${item.td3}</div></td>
                          <td width="100px"><div class="txt">${item.td4}</div></td>
                          <td width="100px"><div class="txt">${item.td5}</div></td>
                      </tr>
                     `
                } else {
                    body += `    <td width="50px"><div class="txt">${item.sort}</div></td>
                <td width="200px"><div class="txt">${item.materialName ?? item.goodsName}${item.giftId !== "0" ? "（赠）" : ""}</div></td>
                <td width="200px"><div class="txt">${item.sku}</div></td>
                <td width="50px"><div class="txt">${item.orderProductCount}</div></td>
                <td width="100px"><div class="txt">${item.orderPrice / 100}</div></td>
                <td width="100px"><div class="txt">${item.detailPayPrice / 100}</div></td>`
                }

                count = count - 1
            }
        } else if (item.isHead) {
            body += `<div class="content">
            <div class="descItem">订单编号：${item.orderCode}</div>
            <div class="descItem">订单时间：${item.createTime}</div>
            <div class="descItem">商户名称：${item.storeName}</div>
            <div class="descItem">客户信息：${item.memberName},${item.memberPhone}</div>
            <div class="descItem">收货信息：${item.memberAddress}</div>
            </div>
            `
            count = count - 2
            body += `<table border='1' cellPadding='0' cellSpacing='0'>`
            body += `  
                  <tbody>
                    <tr>
                        <td width="50px"><div class="txt">${item.ind}</div></td>
                        <td width="200px"><div class="txt">${item.td1}</div></td>
                        <td width="200px"><div class="txt">${item.td2}</div></td>
                        <td width="50px"><div class="txt">${item.td3}</div></td>
                        <td width="100px"><div class="txt">${item.td4}</div></td>
                        <td width="100px"><div class="txt">${item.td5}</div></td>
                    </tr>
                   `
            count = count - 1

        } else if (item.isFoot) {

            body += `
                <tr>
                <td colSpan="3" width="450px"><div class="txt">${item.td6}</div></td>
                <td colSpan="3" width="250px"><div class="txt">${item.td7}</div></td>
                
            </tr>
                
                </tbody></table>`
            count = count - 1
            if (count <= 2) {

                // body += `<div class="pageNo" style="height:${50 * (count - 1)}px">第${pageNo}/${pageNum}页</div>`

                count = pageSize
                return
            }
        } else {
            // 真是数据
            body += `  <tr>
                <td width="50px"><div class="txt">${item.sort}</div></td>
                <td width="200px"><div class="txt">${item.materialName ?? item.goodsName}${item.giftId !== "0" ? "（赠）" : ""}</div></td>
                <td width="200px"><div class="txt">${item.sku}</div></td>
                <td width="50px"><div class="txt">${item.orderProductCount}</div></td>
                <td width="100px"><div class="txt">${item.orderPrice / 100}</div></td>
                <td width="100px"><div class="txt">${item.detailPayPrice / 100}</div></td>
            </tr>`
            count = count - 1
        }

        if (count <= 0) {
            body += ' </tbody></table>'
            if (index === resData.length - 1) {
                // body += `<div class="pageNo">第${pageNo}/${pageNum}页</div>`
                return
            }
            // body += `<div class="pageNo" style="height:${50 * (count - 1)}px">第${pageNo}/${pageNum}页</div>`

            count = pageSize

        }
        // if (index === resData.length - 1) {
        //     body += `<div class="pageNo">第${pageNo}/${pageNum}页</div>`
        // }
    })
    // console.log(body);
    let dom = `
                ${body}
                <div class="footer">
                    <div class="thanks">感谢您选择哈奇马宠物！</div>
                    <div class="tips">
                        <div class="tipsTitle">温馨提示：</div>
                        <div class="tipsText">
                        遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！
                        </div>
                    </div>
                </div>
          `;
    let style = `@page {} body {padding: 20px 50px 20px 50px;}
    .printDom{
        width:700px;
        height:1050px;
        

    }
            td .txt{
                height:50px;
                overflow:hidden;
                font-size:12px;
                display:flex;
                align-items:center;
                justify-content: center;

            }
            .footer,.header{
                height:100px;
                overflow:hidden;
 
                position:relative;
            }
            .descItem{
                height:20px;
                overflow:hidden;

            }
            .pageNo{
                text-align:right;
            }
            .header{
                height:130px;
                text-align:center;

            }
            .header .logo{
                width:160px;
                height:80px;
                position:absolute;
                left:100px;
                top:10px;
            }
            `;

    div.innerHTML = dom;
    div.setAttribute("style", "");
    div.setAttribute("id", "print_area");
    div.setAttribute("class", "printDom");
    document.body.appendChild(div);
    printJs({
        printable: "print_area",
        type: "html",
        style: style, // 亦可使用引入的外部css;
        scanStyles: false,
        repeatTableHeader: false
    });
    document.body.removeChild(document.querySelector("#print_area"));
}
/*
 * tag：所要创建的标签名称
 * attrs: 所需要添加的属性，｛key:val,key:val｝
 */
function makeSVG(tag, attrs) {
    const ns = "http://www.w3.org/2000/svg";
    const xlinkns = "http://www.w3.org/1999/xlink";

    let el = document.createElementNS(ns, tag);
    if (tag === "svg") {
        el.setAttribute("xmlns:xlink", xlinkns);
    }
    for (let k in attrs) {
        if (k === "xlink:href") {
            el.setAttributeNS(xlinkns, k, attrs[k]);
        } else {
            el.setAttribute(k, attrs[k]);
        }
    }
    return el;
}
export function printWaybill(dataSource, sku) {
    console.log(dataSource, "dataSource");
    let svg = makeSVG("svg", { id: "barCodeSvg" });
    JsBarcode(svg, dataSource.orderCode, {
        displayValue: false,
        width: 2,
        height: 50,
        margin: 0,
    });

    let dom = document.createElement("div");
    dom.setAttribute("class", "waybill");
    dom.setAttribute("id", "barcode");

    dom.innerHTML = `
            <div class="code">订单号：${dataSource.orderCode}${dataSource.deliverymanName ? ",配送员：" + dataSource.deliverymanName : ""}</div>
            <img src="${logo}" alt="" class="logo" />
            <div class="recipient ">
                <div class="value">
                <div class="name">商户名：</div><div class="txt">${dataSource.storeName
        }</div>
                </div>
                <div class="value">
                <div class="name">客户信息：</div> <div class="txt">${makeCode(
            dataSource.memberName,
            "mid",
            1,
            dataSource.memberName.length - 1
        )}，${makeCode(dataSource.memberPhone, "mid", 3, 7)}</div>
                </div>
                <div class="value">
                <div class="name">收货信息：</div><div class="txt">${dataSource.memberAddress
        }</div>
                </div>
            </div>
            <div class="sku">
                <div class="value"> 
                <div class="name">商品明细：</div>
                    <div class="txt">
                    ${sku.join("</br>")}
                    </div>
                </div>
            </div>
            <div class="flag">宠圈顶配，养宠必备</div>
            <div class="tips">哈奇马温馨提示:</div>
            <div class="tipTxt">遇到任何问题，请及时与我们联系，联系电话400-078-1213，我们会尽最大能力为您解决，确保您的购物体验！</div>
            <img src="${wxGong}" alt="" class="wxGong" />
      `;
    let canvas = document.createElement("canvas");
    const XML = new XMLSerializer().serializeToString(svg);
    const SVG64 = btoa(XML);
    const image64 = "data:image/svg+xml;base64," + SVG64;
    const img = new Image();
    img.onload = function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    };
    img.src = image64;
    img.setAttribute("class", "img");
    dom.prepend(img);
    document.body.appendChild(dom);
    let style = `@page { margin: 0; } body { padding: 0px;}
    body { padding: 0px}
    .waybill{
        width:95%;
        font-size:12px;
        position:relative;
    }
    .code{
        text-align: center;
        margin-bottom:0;
        font-size:12px;
    }
    .img{
        width:80%;
        margin:0 0 0 10%;                        
    }
    .wxGong{
        width:80px;
        height:80px;
        position:absolute;
        right:20px;
        bottom:40px;
    }
     .logo {
        width: 60px;
        background-color: #000;
        color:#00;
        margin-left:20px;
    }
    .recipient,.sku{
        border-top:1px dashed #000;
        border-left:1px dashed #000;
        border-right:1px dashed #000;
        border-bottom:1px dashed #000;

        padding:10px 0;
    }
    
    
    .recipient .value,.sku .value{
        padding:0 10px;
        display:flex;
        justify-content:space-between;
    }
    .recipient .value .name,.sku .value .name{
        width:70px;
    }
    .recipient .value .txt,.sku .value .txt{
        width:calc(100% - 75px);
    }
    .flag{
        font-weight:600;
        margin:20px 0 40px;

    }
    .tipTxt{
        font-weight:600;
        

    }
    .sku{
        border-bottom:1px dashed #000;
        display:none;
    }
                `;
    setTimeout(() => {
        printJs({
            printable: "barcode",
            type: "html",
            style: style, // 亦可使用引入的外部css;
            scanStyles: false,
        });
        document.body.removeChild(document.querySelector("#barcode"));
    }, 0);
}

export function printLogo() {
    const dom = `<img src="${NewLogo}" alt="" class="logo1" /><img src="${NewLogo}" alt="" class="logo2" />`;
    let div = document.createElement("div");
    div.innerHTML = dom;
    div.setAttribute("id", "print_area");
    div.setAttribute("class", "printDom");
    document.body.appendChild(div);
    printJs({
        printable: "print_area",
        type: "html",
        style: `
                @page { margin: 0;size:portrait ;count:100} 
                body { padding: 0px;position:relative;}
                .logo1{position:absolute;width:100px;height:120px;left:-5px;top:220px}
                .logo2{position:absolute;width:100px;height:120px;left:-5px;top:50px}
                `, // 亦可使用引入的外部css;
        scanStyles: false,
    });
    document.body.removeChild(document.querySelector("#print_area"));
}


// 门店条码
export function printQrCode({ storeName = '', dataSource } = {}, fn) {
    console.log(dataSource, 'dataSource');
    try {
        let dom = ''
        const px2mm = parseFloat((new unitConversion().pxConversionMm(1)).toFixed(2))
        // 二维码内容
        dataSource.forEach((item, index) => {
            const text = item.identificationCode;
            // 生成二维码
            window.QRCode.toDataURL(text, function (err, url) {
                if (err) console.error(err);
                console.log('url=====>>>>', url);
                dom += `
                        <div class="title" style="${index % 2 == 1 ? 'margin-top:20px;' : 'margin-top:50px;'}">${`HAQIMA`}</div>
                        <img src="${url}" alt="" class="logo"  />
                        <div class="name">${storeName}</div>
                        <div class="code" style="${index % 2 == 1 ? 'page-break-after: always;' : ''}">编码:${item.numCode}</div>
                    `

            });
        })
        let div = document.createElement('div')
        div.innerHTML = dom
        div.setAttribute('id', 'print_area')
        div.setAttribute('class', 'printDom')
        document.body.appendChild(div)
        printJs({
            printable: 'print_area',
            type: 'html',
            style: `
            @page { margin: 0 ;size: portrait ;count:1} 
            body { padding: 0px;position:relative;}
            .title{width:30mm;font-size:${14 * px2mm}mm;font-weight:bold;text-align:center;margin-left:${-14 * px2mm}mm}
            .logo{width:25mm;height:25mm;margin-left:${-6 * px2mm}mm} 
            .name{width:30mm;font-size:${9 * px2mm}mm;text-align:center;margin-left:${-16 * px2mm}mm;margin-top:${-6 * px2mm}mm}
            .code{width:30mm;font-size:${8 * px2mm}mm;text-align:center;margin-left:${-16 * px2mm}mm;margin-top:${3 * px2mm}mm}
            `,// 亦可使用引入的外部css;
            scanStyles: false,
            onLoadingEnd() {
                fn && fn()
            },
            onError() {
                fn && fn()
                alert('打印异常，请重试或联系管理员')
            }
        })
        document.body.removeChild(document.querySelector("#print_area"));

    } catch (err) {

    }
}